package com.nintendo.frame;

import com.nintendo.entity.pojo.Category;
import com.nintendo.entity.pojo.Dish;
import com.nintendo.mapper.CategoryDao;
import com.nintendo.mapper.DishDao;
import com.nintendo.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class DishFrame extends JFrame {

    private JTextField nameField;
    private JComboBox<Category> categoryComboBox; // 使用 JComboBox 替换 JTextField
    private JTextField codeField;
    private JTextField unitField;
    private JTextField priceField;
    private JTextField statusField;

    public DishFrame() {
        setTitle("菜品信息管理");
        setSize(400, 350); // 调整窗口大小以适应新的按钮
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 关闭当前页面
        setLocationRelativeTo(null);

        // 创建面板
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;

        // 添加组件
        addComponent(panel, new JLabel("菜品名:"), gbc, 0, 0);
        addComponent(panel, nameField = new JTextField(20), gbc, 1, 0);

        // 查询数据库中的类别数据并填充到 JComboBox
        List<Category> categories = loadCategoriesFromDatabase();
        categoryComboBox = new JComboBox<>(categories.toArray(new Category[0]));
        categoryComboBox.setRenderer(new CategoryRenderer()); // 设置自定义渲染器
        addComponent(panel, new JLabel("菜品类别:"), gbc, 0, 1);
        addComponent(panel, categoryComboBox, gbc, 1, 1);
        addComponent(panel, new JLabel("菜品编码:"), gbc, 0, 2);
        addComponent(panel, codeField = new JTextField(20), gbc, 1, 2);

        addComponent(panel, new JLabel("单位:"), gbc, 0, 3);
        addComponent(panel, unitField = new JTextField(20), gbc, 1, 3);

        addComponent(panel, new JLabel("单价:"), gbc, 0, 4);
        addComponent(panel, priceField = new JTextField(20), gbc, 1, 4);

        addComponent(panel, new JLabel("状态:"), gbc, 0, 5);
        addComponent(panel, statusField = new JTextField(20), gbc, 1, 5);

        // 添加按钮
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

        JButton saveButton = new JButton("确定");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveDish();
            }
        });
        buttonPanel.add(saveButton);

        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose(); // 关闭当前页面
            }
        });
        buttonPanel.add(cancelButton);

        gbc.gridx = 0;
        gbc.gridy = 6;
        gbc.gridwidth = 2;
        panel.add(buttonPanel, gbc);

        add(panel);
    }

    private void addComponent(JPanel panel, JComponent component, GridBagConstraints gbc, int x, int y) {
        gbc.gridx = x;
        gbc.gridy = y;
        panel.add(component, gbc);
    }

    private void saveDish() {
        Dish dish = new Dish();
        dish.setName(nameField.getText());
        try {
            Category selectedCategory = (Category) categoryComboBox.getSelectedItem();
            if (selectedCategory != null) {
                dish.setCategoryid(selectedCategory.getId()); // 使用 Category 的 id
            } else {
                throw new NumberFormatException("请选择一个有效的菜品类别");
            }
            dish.setCode(codeField.getText());
            dish.setUnit(unitField.getText());
            dish.setPrice(Double.parseDouble(priceField.getText()));
            dish.setStatus(statusField.getText());

            // 保存到数据库
            try (SqlSession session = MyBatisUtils.getSqlSession()) {
                DishDao mapper = session.getMapper(DishDao.class);
                mapper.insert(dish);
                session.commit();
            }
            // 刷新页面
            DishListFrame dishListFrame = new DishListFrame();
            dishListFrame.refreshTable();
            JOptionPane.showMessageDialog(this, "菜品信息已保存");
            dispose(); // 关闭当前页面
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "请输入有效的数字格式", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private List<Category> loadCategoriesFromDatabase() {
        try (SqlSession session = MyBatisUtils.getSqlSession()) {
            CategoryDao mapper = session.getMapper(CategoryDao.class);
            return mapper.selectAll();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new DishFrame().setVisible(true);
            }
        });
    }

    // 自定义渲染器类
    private static class CategoryRenderer extends JLabel implements ListCellRenderer<Category> {

        public CategoryRenderer() {
            setOpaque(true);
        }

        @Override
        public Component getListCellRendererComponent(JList<? extends Category> list, Category value, int index, boolean isSelected, boolean cellHasFocus) {
            if (value != null) {
                setText(value.getName()); // 显示 Category 的 name 属性
            } else {
                setText("");
            }

            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }

            return this;
        }
    }
}
